import axios from 'axios'
import { ElMessage } from 'element-plus'
import userStore from '@/store/modules/user'
import {IsCheckTimeOut} from './time'
import {useRouter} from 'vue-router'

let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})

// 控制登录过期的锁
let isRefreshing = false

// 请求拦截器
request.interceptors.request.use((config) => {
  // const usestore = userStore()
  // const router = useRouter()
  const store = userStore()
  if (store.token) {
    config.headers.token = store.token
    // if(IsCheckTimeOut()){
    //   ElMessage.error('token超时了')
    //   usestore.userLogout()
    //   router.replace('/login')
    //   return false
    // }
  }
  return config
})
// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const code: number = response.data.code
    if (!code || code === 200) {
      return response.data
    }
    if (code === 401) {
      // 防止多次弹出登录框
      if (isRefreshing) return Promise.reject(response.data)
      // 清除本地过去的登录状态
      // 跳转到登录页
      
      // 在内部消化掉这个业务异常
      return Promise.reject(response)
    }

    // 其他错误情况
    ElMessage.error(response.data.data.message || '请求失败，请稍后重试')
    return Promise.reject(response.data)
  },
  (error) => {
    //处理网络错误
    let msg = ''
    let status = error.response.status
    switch (status) {
      case 401:
        msg = 'token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      default:
        msg = '无网络'
    }
    ElMessage.error(msg)
    return Promise.reject(error)
  },
)

export default request
